package com.example.license.client.event;

import com.example.license.client.domain.LicenseVerify;
import com.example.license.client.domain.LicenseVerifyParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * 在项目启动时安装证书
 */
public class LicenseCheckListener implements ApplicationListener<ContextRefreshedEvent> {

    public LicenseCheckListener() {
        System.out.println("wo shi jian ting qi wo chu shi hua le");
    }

    /**
     * 证书subject
     */
    @Value("${license.subject:license_sub}")
    private String subject;

    /**
     * 公钥别称
     */
    @Value("${license.publicAlias:publicCert}")
    private String publicAlias;

    /**
     * 访问公钥库的密码
     */
    @Value("${license.storePass:abc@123}")
    private String storePass;

    /**
     * 证书生成路径
     */
    @Value("${license.licensePath:F:/keytool/license.lic}")
    private String licensePath;

    /**
     * 密钥库存储路径
     */
    @Value("${license.publicKeysStorePath:F:/keytool/publicCerts.keystore}")
    private String publicKeysStorePath;

    public static boolean isStart = true;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //root application context 没有parent
        //此处判断主要是用于解决web应用中的重复刷新问题，因为web应用中会存在父子容器，导致
        //事件ContextRefreshedEvent会被触发多次。通过限定只在父容器刷新事件触发时才进行
        //处理,从而解决多次触发问题。
        //ApplicationContext context = event.getApplicationContext().getParent();
        //if(context == null){
        if(isStart){
            if(StringUtils.isNotBlank(licensePath)){
                System.out.println("++++++++ 开始安装证书 ++++++++");
                LicenseVerifyParam param = new LicenseVerifyParam();
                param.setSubject(subject);
                param.setPublicAlias(publicAlias);
                param.setStorePass(storePass);
                param.setLicensePath(licensePath);
                param.setPublicKeysStorePath(publicKeysStorePath);
                LicenseVerify licenseVerify = new LicenseVerify();
                //安装证书
                try {
                    licenseVerify.install(param);
                    System.out.println("++++++++ 证书安装成功 ++++++++");
                } catch (Exception e) {
                }
            }
            isStart = false;
        }
    }
}
